<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;

/**
 * 节气管理
 * @ApiWeigh (96)
 */
class Jieqi extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    
    /**
     * 获取节气信息
     * 
     * @ApiTitle    (获取节气信息)
     * @ApiSummary  (根据指定年份获取24节气的具体时间，支持农历和公历查询)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/jieqi/getJieqi)
     * @ApiParams   (name="year", type="integer", required=true, description="年份，如：2024")
     * @ApiParams   (name="month", type="integer", required=true, description="月份，1-12之间的数字")
     * @ApiParams   (name="day", type="integer", required=true, description="日期，1-31之间的数字")
     * @ApiParams   (name="type", type="integer", required=true, description="历法类型：0=农历，1=公历", default=0)
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": [{
          "jieqi_name": "小寒",
          "jieqi_simple_time": "2024-01-06",
          "jieqi_detail_time": "2024-01-06 04:49:09",
          "jieqi_simple_lunar_time": "2023-11-25",
          "jieqi_detail_lunar_time": "2023-11-25 04:49:09"
        }]
      })
     */
    public function getJieqi()
    {
        $year = $this->request->param('year', date('Y'), 'intval');
        $month = $this->request->param('month', 1, 'intval');
        $day = $this->request->param('day', 1, 'intval');
        $type = $this->request->param('type', 0, 'intval');
        
        try {
            // 先查询缓存
            $cache = \app\common\model\JieqiLog::where([
                'year' => $year,
            ])->find();
            
            if($cache) {
                $this->success('获取成功', json_decode($cache['data'], true));
            }
            
            $params = [
                'type' => $type,
                'year' => $year,
                'month' => $month,
                'day' => $day,
                'jieqi' => 1
            ];
            
            $result = YuanfenjuService::instance()->request('/Gongju/jieqi', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'].'---' ?? '获取节气数据失败');
            }
            
            // 记录查询日志
            \app\common\model\JieqiLog::create([
                'year' => $year,
                'type' => $type,
                'month' => $month,
                'day' => $day,
                'data' => json_encode($result['data']),
                'createtime' => time()
            ]);
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }
}